package com.hnevc.asyncokhttp3demo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ShowFoodActivity extends AppCompatActivity {

    List<Food> mFoodList;
    ListView mListView;
    ImageButton mBtnEdit;
    private MyBaseAdapter mAdapter;

    Food food;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_food);
        food = (Food) getIntent().getSerializableExtra("food");
        initView();
        initEvent();
        initData();
    }

    private void initEvent() {
        mBtnEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO 调用SettingActivity
                Intent intent = new Intent();
                intent.setClass(ShowFoodActivity.this,SettingActivity.class);
                startActivity(intent);
            }
        });
    }

    private void initView() {
        mListView = (ListView) findViewById(R.id.id_lv_food_list);
        mBtnEdit = (ImageButton) findViewById(R.id.id_ib_edit);
    }

    /**
     * 初始化数据，用来获取食物列表的数据
     */
    private void initData() {
        OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(new MyCookieJar(this))
                .build();
        Request request;
        if (food == null) {
            //访问网络获取数据
            request = new Request.Builder()
                    .url("http://" + getResources().getString(R.string.ServerIp) + ":8080/RestaurantServer/Food/getFoods")
                    .get()
                    .build();
        } else {
            RequestBody body = new FormBody.Builder()
                    .add("foodPrice", food.getFoodPrice() + "")
                    .add("foodHot", food.getFoodHot() + "")
                    .add("foodFish", food.getFoodFish() + "")
                    .add("foodSour", food.getFoodSour() + "")
                    .build();
            request = new Request.Builder()
                    .url("http://" + getResources().getString(R.string.ServerIp) + ":8080/RestaurantServer/Food/doFindFoods")
                    .post(body)
                    .build();
        }
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(ShowFoodActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() != 200) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ShowFoodActivity.this, "用户名密码错误！", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent();
                            intent.setClass(ShowFoodActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    });
                } else {


                    String s = response.body().string();
                    Gson gson = new Gson();

                    mFoodList = gson.fromJson(s, new TypeToken<List<Food>>() {
                    }.getType());

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter = new MyBaseAdapter();
                            mListView.setAdapter(mAdapter);
                        }
                    });

                }
            }
        });


    }

    //自定义数据适配器
    class MyBaseAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mFoodList.size();
        }

        @Override
        public Object getItem(int position) {
            return mFoodList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return mFoodList.get(position).getFoodId();
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                View view = LayoutInflater.from(ShowFoodActivity.this).inflate(R.layout.food_list_item, null);


                viewHolder = new ViewHolder();
                viewHolder.mTvFoodName = (TextView) view.findViewById(R.id.id_tv_foodName);
                viewHolder.mTvFoodPrice = (TextView) view.findViewById(R.id.id_tv_foodPrice);
                viewHolder.mIvFoodPic = (ImageView) view.findViewById(R.id.id_iv_foodPic);
                viewHolder.mTvFoodDesc = (TextView) view.findViewById(R.id.id_tv_foodDesc);
                view.setTag(viewHolder);

                convertView = view;
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            Food food = mFoodList.get(position);
            viewHolder.mTvFoodName.setText(food.getFoodName());
            viewHolder.mTvFoodPrice.setText(food.getFoodPrice() + "");

            String url = "http://" + getResources().getString(R.string.ServerIp)
                    + ":8080/RestaurantServer/uploadFoodImage/"
                    + food.getFoodPic();
            Picasso.with(ShowFoodActivity.this)
                    .load(url)
                    .into(viewHolder.mIvFoodPic);

            viewHolder.mTvFoodDesc.setText(food.getFoodDesc());
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra("foodId",mFoodList.get(position).getFoodId());
                    intent.setClass(ShowFoodActivity.this, FoodDetailActivity.class);
                    startActivity(intent);
                }
            });
            return convertView;
        }
    }

    class ViewHolder {
        TextView mTvFoodName;
        TextView mTvFoodPrice;
        TextView mTvFoodDesc;
        ImageView mIvFoodPic;
    }
}
